package cn.crex1.xiaomi.core.mvc.context;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.crex1.xiaomi.core.mvc.context.web.ConfigWebContext;
import cn.crex1.xiaomi.core.mvc.util.ClassUtil;
import cn.crex1.xiaomi.core.mvc.util.PropertiesUtil;

public class ContextLoader {
	
	private static final String CONTEXT = "context";


	private ThreadLocal<ClassLoader> currentClassLoader = new ThreadLocal<>();

	private ConfigWebContext cwc;

	private static String contextProperties = null;

	private static Logger logger = LoggerFactory.getLogger(ContextLoader.class);
	
	public ContextLoader() {
		cwc = new ConfigWebContext();
	}

	static {
		contextProperties = PropertiesUtil.getContextProperties(ContextLoader.class);
		if (contextProperties == null) {
			logger.error("加载配置失败");
		}
	}

	private WebContext initWebContext(ServletContext Context) {
		Class<?> loadDefineClass = ClassUtil.loadDefineClass(contextProperties, getCurrentClassLoader());

		logger.info("Root WebContext inited start");

		Object instanceClass = ClassUtil.instanceClass(loadDefineClass);
		if (!(instanceClass instanceof ConfigWebContext)) {
			try {
				throw new Exception("Container instantiation error");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Context.setAttribute(CONTEXT, instanceClass);
		cwc.setContext(Context);
		cwc.start();
		cwc.refresh();
		logger.info("Root WebContext inited finished");
		return cwc;

	}

	public void createWebContext(ServletContext Context) {
		if (!cwc.isclose()) {
			logger.error("webcontext Already exist");
			try {
				throw new Exception("webcontext Already exist");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		if (currentClassLoader.get() == null) {
			currentClassLoader.set(Context.getClassLoader());
			Thread.currentThread().setContextClassLoader(getCurrentClassLoader());
		}
		
		initWebContext(Context);

	}
	
	public void destroyWebContext() {
		if (!cwc.isclose()) {
			cwc.stop();
			logger.error("WebContext closed finished");
		}
	}
	
	public ClassLoader getCurrentClassLoader() {
		return currentClassLoader.get();
	}

	public void setCurrentClassLoader(ClassLoader currentClassLoader) {
		this.currentClassLoader.set(currentClassLoader);
	}

}
